package com.example.gateway.filter;

import com.example.common.constant.HttpHeaders;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Objects;

/**
 * @author Destinycc
 */
@Component("pathKeyResolver")
@Primary
public class PathKeyResolver extends CustomKeyResolver {
    public static final String BEAN_NAME = "pathKeyResolver";

    @Override
    public Mono<String> resolve(ServerWebExchange exchange) {
        String appId = exchange.getRequest().getHeaders().getFirst(HttpHeaders.APP_ID);
        if (Objects.isNull(appId)){
            appId = exchange.getRequest().getHeaders().getFirst("X-Forwarded-For") == null ?
                    Objects.requireNonNull(exchange.getRequest().getRemoteAddress()).getHostString() : Objects.requireNonNull(exchange.getRequest().getHeaders().getFirst("X-Forwarded-For"));
        }
        return Mono.just(
                appId + exchange.getRequest().getURI().getPath()
        );
    }

    @Override
    public String getBeanName(){
        return BEAN_NAME;
    }
}
